package com.tingfeng.xiuzhen;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.tauth.IUiListener;
import com.tingfeng.xiuzhen.eventbus.MessageEvent;
import com.tingfeng.xiuzhen.http.OkHttpUtils;
import com.tingfeng.xiuzhen.qq.BaseUiListener;
import com.tingfeng.xiuzhen.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_result;
    // QQ登录回调
    private IUiListener qqLoginListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 注册EventBus
        EventBus.getDefault().register(this);
        initView();
        initQQLoginListener();
    }

    private void initView() {
        tv_result = (TextView) findViewById(R.id.tv_result);
        Button btn_qq_login = (Button) findViewById(R.id.btn_qq_login);
        btn_qq_login.setOnClickListener(this);
        Button btn_qq_logout = (Button) findViewById(R.id.btn_qq_logout);
        btn_qq_logout.setOnClickListener(this);
        Button btn_wx_login = (Button) findViewById(R.id.btn_weixin_login);
        btn_wx_login.setOnClickListener(this);
    }

    /****************** QQ相关 start ******************/
    // QQ登录回调
    private void initQQLoginListener() {
        qqLoginListener = new BaseUiListener() {
            @Override
            protected void doComplete(JSONObject values) throws JSONException {
                //{"auth_time":"1527600141911","ret":"0","pay_token":"","pf":"desktop_m_qq-10000144-android-2002-","page_type":"1",
                // "expires_time":1535376201953,"openid":"","expires_in":"7776000","pfkey":"8b372551e05c1b82a131de8d16cb691f",
                // "access_token":"DC92D06A6458A3CE2D54C343C61F9100"}
                if (values.getInt("ret") == 0) {
                    MyApplication.mTencent.setOpenId(values.getString("openid"));
                    MyApplication.mTencent.setAccessToken(values.getString("access_token"), values.getString("expires_in"));
                    // 保存QQToken
                    saveQQToken(values);
                    // 如需获取unionid,可getQQUnionId(values)
                    // 获取用户信息
                    getQQUserInfo();
                } else {
                    logoutQQ();
                    loginQQ();
                }
            }

            @Override
            public void onCancel() {
                ToastUtils.showShortToast("取消QQ登录");
                tv_result.setText("取消QQ授权");
            }
        };
    }

    // QQ登录
    private void loginQQ() {
        if (!checkQQTokenValid()) {
            tv_result.setText("QQ登录授权...");
            MyApplication.mTencent.login(MainActivity.this, "", qqLoginListener);
        } else {
            SharedPreferences sp = getSharedPreferences("thirdlogin", Context.MODE_PRIVATE);
            MyApplication.mTencent.setOpenId(sp.getString("qq_openid", ""));
            MyApplication.mTencent.setAccessToken(sp.getString("qq_access_token", ""), sp.getString("qq_expires_in", ""));
            getQQUserInfo();
        }
    }

    // QQ注销登录
    private void logoutQQ() {
        MyApplication.mTencent.logout(MyApplication.getAppContext());
        tv_result.setText("QQ已注销");
        SharedPreferences sp = getSharedPreferences("thirdlogin", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove("qq_expires_time");
        editor.commit();
    }


    // 存储QQToken
    private void saveQQToken(JSONObject data) throws JSONException {
        SharedPreferences sp = getSharedPreferences("thirdlogin", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("qq_expires_time", data.getString("expires_time"));
        editor.putString("qq_access_token", data.getString("access_token"));
        editor.putString("qq_expires_in", data.getString("expires_in"));
        editor.putString("qq_openid", data.getString("openid"));
        editor.commit();
    }

    // 校验QQToken是否有效
    private boolean checkQQTokenValid() {
        SharedPreferences sp = getSharedPreferences("thirdlogin", Context.MODE_PRIVATE);
        String expires_time = sp.getString("qq_expires_time", "0");

        long var7 = Long.parseLong(expires_time);
        long var9 = System.currentTimeMillis();
        if (var9 < var7) {
            String access_token = sp.getString("qq_access_token", null);
            String expires_in = sp.getString("qq_expires_in", null);
            String openid = sp.getString("qq_openid", null);
            MyApplication.mTencent.setOpenId(openid);
            MyApplication.mTencent.setAccessToken(access_token, expires_in);
            return true;
        } else {
            return false;
        }
    }

    // 获取QQ用户信息
    private void getQQUserInfo() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", MyApplication.mTencent.getAccessToken());
        params.put("oauth_consumer_key", GlobalData.QQ_APP_ID);
        params.put("openid", MyApplication.mTencent.getOpenId());

        OkHttpUtils.getInstance().getRequestAsync(GlobalData.QQ_GET_USER_INFO, params, new OkHttpUtils.MyOkHttpCall() {
            @Override
            public void success(Call call, Response response) throws IOException {
                // response.body()只可调用一次
                final String resultString = response.body().string();
                Log.d(GlobalData.TAG, "http_getuserinfo: " + resultString);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject resultObj = new JSONObject(resultString);
                            if (resultObj.getInt("ret") == 0) {
                                tv_result.setText("QQ昵称:" + resultObj.getString("nickname"));
                            } else {
                                logoutQQ();
                                loginQQ();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    /****************** QQ相关 end ******************/

    /****************** 微信相关 start ******************/
    private void loginWeixin() {
        if (MyApplication.wxApi.isWXAppInstalled() && MyApplication.wxApi.isWXAppSupportAPI()) {
            final SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";//应用授权作用域
            req.state = "wechat_sdk_demo";//用于保持请求和回调的状态，授权请求后原样带回给第三方。
            MyApplication.wxApi.sendReq(req);
        } else {
            ToastUtils.showShortToast("未安装微信");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
        // 获取微信授权code
        String code = messageEvent.getMessage();
        // 获取token，openid
        // 获取个人信息
        getWxToken(code);
    }

    // 通过code获取access_token
    private void getWxToken(String code) {
        Map<String, String> params = new HashMap<>();
        params.put("appid", GlobalData.WX_APP_ID);
        params.put("secret", GlobalData.WX_APP_SECRET);
        params.put("code", code);
        params.put("grant_type", "authorization_code");

        //{"access_token":"11_-T4RsKGs8-SXKCtdYUkaHpx5AZyTCmaQRk6SWR0ZcwKYjcvY0eDJljhx683N1aNJ2j0bO8ndnu8ZuQGTlooPxB8dR8iK_g81sggRH6ZhPEA",
        // "expires_in":7200,"refresh_token":"11_Vn-rr9i57WDrH4YjxWg_R1qdRfXZusmAwXvl7WSJfvGeMRYx215dKbtWKFh9LA0Bothg6mIRTp_yJjuP3cbBaEhjoZAhT_l3aHnJGGpnAUc",
        // "openid":"xxx","scope":"snsapi_userinfo","unionid":"xxx"}
        OkHttpUtils.getInstance().getRequestAsync(GlobalData.WX_GET_TOKEN, params, new OkHttpUtils.MyOkHttpCall() {
            @Override
            public void success(Call call, Response response) throws IOException {
                // response.body()只可调用一次
                final String resultString = response.body().string();
                Log.d(GlobalData.TAG, "http_wx_getToken: " + resultString);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject resultObj = new JSONObject(resultString);
                            if (resultObj.getString("access_token") != null) {
                                String access_token = resultObj.getString("access_token");
                                String openid = resultObj.getString("openid");
                                getWxUserInfo(access_token, openid);
                            } else {
                                Log.e(GlobalData.TAG, "run_err: " + resultObj.toString());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    // 获取用户个人信息（UnionID机制）
    private void getWxUserInfo(String access_token, String openid) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", access_token);
        params.put("openid", openid);
        //{"openid":"xxx","nickname":"Animal_1","sex":1,"language":"zh_CN","city":"Xi'an","province":"Shaanxi","country":"CN",
        // "headimgurl":"http:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/DYAIOgq83erSSvDC5t1xWD7CiaicGFtZptRtwPKP969ygibS212MnSG72Cv9XoehOKCSQBIepsjYp3ricDPGzic923g\/132",
        // "privilege":[],"unionid":"xxxxx"}
        OkHttpUtils.getInstance().getRequestAsync(GlobalData.WX_GET_USER_INFO, params, new OkHttpUtils.MyOkHttpCall() {
            @Override
            public void success(Call call, Response response) throws IOException {
                // response.body()只可调用一次
                final String resultString = response.body().string();
                Log.d(GlobalData.TAG, "http_wx_getUserInfo: " + resultString);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject resultObj = new JSONObject(resultString);
                            if (resultObj.getString("nickname") != null) {
                                tv_result.setText("微信nickname:" + resultObj.getString("nickname"));
                            } else {
                                Log.e(GlobalData.TAG, "run_err: " + resultObj.toString());
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    /****************** 微信相关 end ******************/

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_qq_login:
                loginQQ();
                break;
            case R.id.btn_qq_logout:
                logoutQQ();
                break;
            case R.id.btn_weixin_login:
                loginWeixin();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //QQ登录回调需添加
        MyApplication.mTencent.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
